#import "BackgroundView.h"
#import "NetworkController.h"



@implementation BackgroundView
@synthesize map;
@synthesize scale;
@synthesize tileSize;
@synthesize currentPoint;
@synthesize backgroundActivated;
@synthesize changeAllBackgroundActivated;

+ (Class)layerClass {
	return [CATiledLayer class];
}

- (id)initWithMap:(Map *)newMap withTileSize:(CGSize)size withScale:(int)scale {
    if ((self = [super initWithFrame:CGRectMake(0, 0, newMap.size.width, newMap.size.height)])) {
        self.map = newMap;
        CATiledLayer *tiledLayer = (CATiledLayer *)[self layer];
        tiledLayer.tileSize = size;
		tiledLayer.levelsOfDetail = 3;
		tiledLayer.levelsOfDetailBias = 2;
		if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
			tiledLayer.levelsOfDetail = 2;
			tiledLayer.levelsOfDetailBias = 1;
		}
		self.scale = scale;
		tileSize = (CGSize){tiledLayer.tileSize.width/self.scale, tiledLayer.tileSize.height/self.scale};
		drawFirstSquare = NO;
		backgroundActivated = NO;
        changeAllBackgroundActivated = NO;
    }
    return self;
}

- (void)dealloc {
    [map release];
    map = nil;
    [super dealloc];
}

- (void)drawRect:(CGRect)rect {
    // calculate the rows and columns of tiles that intersect the rect we have been asked to draw
    int firstCol = floorf(CGRectGetMinX(rect) / tileSize.width);
    int lastCol = floorf((CGRectGetMaxX(rect)-1) / tileSize.width);
    int firstRow = floorf(CGRectGetMinY(rect) / tileSize.height);
    int lastRow = floorf((CGRectGetMaxY(rect)-1) / tileSize.height);

    for (int row = firstRow; row <= lastRow; row++) {
        for (int col = firstCol; col <= lastCol; col++) {
            CGRect tileRect = CGRectMake(tileSize.width * col, tileSize.height * row,
                                         tileSize.width, tileSize.height);
            tileRect = CGRectIntersection(self.bounds, tileRect);
            CGLayerRef tile = [map backgroundForPoint:CGPointMake(col, row)];
            CGContextDrawLayerInRect(UIGraphicsGetCurrentContext(), tileRect, tile);
        }
    }
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
	drawFirstSquare = YES;
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject];
	lastPoint = [touch previousLocationInView:self];
	currentPoint = [touch locationInView:self];
	CGPoint lastGridCoords = [self convertCoordsToGridCoords:CGPointMake(lastPoint.x, lastPoint.y)];
	CGPoint gridCoords = [self convertCoordsToGridCoords:CGPointMake(currentPoint.x, currentPoint.y)];
	if (!CGPointEqualToPoint(gridCoords, lastGridCoords) || drawFirstSquare) {
		drawFirstSquare = NO;
        NSString *path;
        if(![LoadedImages sharedLoadedImages].eraserActivated) {
            path = [LoadedImages sharedLoadedImages].selectedBackgroundImage;
        } else {
            path = NULL;
        }
		
		[self updateBackgroundAtPoint:gridCoords withImagePath:path];
	} 
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
	UITouch *touch = [touches anyObject];
	lastPoint = [touch locationInView:self];
	CGPoint gridCoords = [self convertCoordsToGridCoords:CGPointMake(lastPoint.x, lastPoint.y)];
    NSString *path;
    if(![LoadedImages sharedLoadedImages].eraserActivated) {
        path = [LoadedImages sharedLoadedImages].selectedBackgroundImage;
    } else {
        path = NULL;
    }
	[self updateBackgroundAtPoint:gridCoords withImagePath:path];
}

- (void)updateBackgroundAtPoint:(CGPoint)point withImagePath:(NSString *)path {
    [map setTileImage:[path lastPathComponent] atPoint:point];
    [map submitChangesToTiles:NO];
    [(BackgroundProtocol *)[[NetworkController sharedNetworkController].networkProtocols objectForKey:([NSString stringWithString:@"BGP"])] sendBackground:path atPoint:point];
    [self setNeedsDisplayInRect:CGRectMake(point.x*tileSize.width, point.y*tileSize.height, tileSize.width, tileSize.height)];
    /*NSArray *tiledImages = [[LoadedImages sharedLoadedImages].tiledBackgroundImages objectForKey:path];
     if (!tiledImages) {
     NSArray *arr = [path componentsSeparatedByCharactersInSet:
     [NSCharacterSet characterSetWithCharactersInString:@"_"]];
     NSLog(@"%@", arr);
     tiledImages = [Token tileImage:image withWidth:[[arr objectAtIndex:[arr count] -2] intValue] withHeight:[[[arr objectAtIndex:[arr count] -1] stringByDeletingPathExtension] intValue]];
     [[LoadedImages sharedLoadedImages].tiledTokenImages setObject:tiledImages forKey:path];
     }*/
}

- (CGPoint)convertCoordsToGridCoords:(CGPoint)coords{
	uint x;
	uint y;
	x = (uint)coords.x / (uint)tileSize.width;
	y = (uint)coords.y / (uint)tileSize.height;
	return CGPointMake(x, y);
}

@end
